import Ajax from '@/utils/ajax';
import tool from '@/utils/tool';
import _ from 'lodash';

export default class SourceData {
  constructor(conf = {}) {
    const {
      convert,
      convertParams,
      propsName = 'props.sourceData',
      context,
    } = conf;
    this.conf = conf;

    if (context) {
      this.getSourceData = () => {
        return _.get(context, propsName, {});
      };
    } else {
      this.getSourceData = () => {
        return conf;
      };
    }
  }

  //异步获取数据
  getRemoteSource(conf = {}, returnPromise = true) {
    let sourceData = this.getSourceData();
    const {
      url,
      method = 'get',
      params,
      server,
      convert,
      convertParams,
    } = sourceData;
    if (!url && !server) {
      if (returnPromise) {
        return Promise.reject('');
      }
      return;
    }
    let _params = Object.assign({}, params, conf.params);
    if (convertParams || conf.convertParams || this.conf.convertParams) {
      _params = tool.pipeFun(
        convertParams,
        conf.convertParams,
        this.conf.convertParams,
      );
    }

    let _server;
    if (server) {
      _server = server(_params);
    }
    if (url) {
      _server = Ajax[method](url, _params);
    }

    //保留资源最初信息
    _server = _server.then((res) => {
      this.remoteSourceDetail = res;
      return res;
    });

    //资源信息解析
    if (convert || conf.convert || this.conf.convert) {
      _server = _server.then((res) => {
        return tool.pipeFun(res, convert, conf.convert, this.conf.convert);
      });
    }
    return _server.then((source) => {
      this.remoteSource = source;
      return source;
    });
  }

  //获取资源详情
  getSourceDetail() {
    let sourceData = this.getSourceData();
    const { sourceDetail } = sourceData;
    if (sourceDetail) {
      return sourceDetail;
    }
    if (this.remoteSourceDetail) {
      return this.remoteSourceDetail;
    }
    return {};
  }

  //获取数据
  getSource = () => {
    let sourceData = this.getSourceData();
    const { convert, source } = sourceData;

    if (this.remoteSource) {
      return this.remoteSource;
    }

    if (source) {
      //固定资源信息解析
      if (convert || this.conf.convert) {
        return tool.pipeFun(source, convert, this.conf.convert);
      }
      return source;
    }
  };

  //初始化数据
  initSource(conf) {
    let p = this.getRemoteSource(conf, false);
    if (!p) {
      return Promise.resolve(this.getSource());
    }
    return p;
  }
}
